package com.itzzj.guacamole.websocket;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.net.GuacamoleSocket;
import org.apache.guacamole.net.GuacamoleTunnel;
import org.apache.guacamole.net.InetGuacamoleSocket;
import org.apache.guacamole.net.SimpleGuacamoleTunnel;
import org.apache.guacamole.protocol.ConfiguredGuacamoleSocket;
import org.apache.guacamole.protocol.GuacamoleClientInformation;
import org.apache.guacamole.protocol.GuacamoleConfiguration;
import org.apache.guacamole.websocket.GuacamoleWebSocketTunnelEndpoint;
import org.springframework.stereotype.Component;

import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


@ServerEndpoint(value = "/tunnel/ws", subprotocols = "guacamole")
@Component
public class WebSocketTunnel extends GuacamoleWebSocketTunnelEndpoint {

    @Override
    protected GuacamoleTunnel createTunnel(Session session, EndpointConfig endpointConfig) throws GuacamoleException {
        System.out.println("sessionMap:" + session.getRequestParameterMap());
        // 通过前端Vue或者其他前端语言请求后端时动态添加参数可使得下方远程windows服务地址动态注入
//        Integer height = Integer.valueOf(session.getRequestParameterMap().get("height").get(0));
//        Integer width = Integer.valueOf(session.getRequestParameterMap().get("width").get(0));
        GuacamoleClientInformation information = new GuacamoleClientInformation();
        information.setOptimalScreenHeight(1080);
        information.setOptimalScreenWidth(1920);
        //guacamole server地址 r端口
        String hostname = "192.168.101.20";
        int port = 4822;
        GuacamoleConfiguration configuration = new GuacamoleConfiguration();
        configuration.setProtocol("rdp");
        // 远程windows服务的地址
        configuration.setParameter("hostname", "192.168.101.6");
        configuration.setParameter("port", "3389");
        configuration.setParameter("username", "1175974811@qq.com");
        configuration.setParameter("password", "720520...");
        configuration.setParameter("ignore-cert", "true");
        // 设置超时连接时长为30分钟（单位：毫秒）
        session.setMaxIdleTimeout(30 * 60 * 1000);



        GuacamoleSocket socket = new ConfiguredGuacamoleSocket(
                new InetGuacamoleSocket(hostname, port),
                configuration,
                information
        );

        GuacamoleTunnel tunnel = new SimpleGuacamoleTunnel(socket);
        return tunnel;
    }

    public void onOpen(Session session) {
        // 当客户端连接建立时调用
        System.out.println("WebSocket连接已建立");
    }
    public void onMessage(String message, Session session) {
        // 当接收到客户端消息时调用
        System.out.println("接收到消息：" + message);

        // 在这里根据接收到的消息做出相应的处理逻辑
        String response = "服务器已收到消息：" + message;

        // 发送响应消息给客户端
        try {
            session.getBasicRemote().sendText(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void onClose(Session session){
        //判断当前连接是否还在线
        if (session.isOpen()) {
            try {
                // 关闭连接
                CloseReason closeReason = new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "进行关闭！");
                session.close(closeReason);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }


    private String getNowTime() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
    }
}